package com.spr.test.springboot.controller;


import com.spr.test.springboot.dao.UserinfoDao;
import com.spr.test.springboot.entity.UserInfo;
import com.spr.test.springboot.shiro.CryptographyUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;



@Controller
@RequestMapping(value = "/")

public class HomeController {

    Logger logger =Logger.getLogger(this.getClass());

    @Autowired
    private UserinfoDao userinfoDao ;

    @GetMapping({"/","/login"})
    public String login() {
        return "sys/login";
    }

    @GetMapping({"/success"})
    public String success() {
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        logger.info(SecurityUtils.getSubject().getSession().getTimeout());
        logger.error(userInfo.getUsername()+"---"+userInfo.getPassword());
        return "sys/success";
    }

    @GetMapping({"/index"})
    public String index() {
        return "sys/index";
    }

    @GetMapping({"/register"})
    public String register() {
        return "sys/register";
    }

    @GetMapping({"/logOut"})
    public String logOut() {

        Subject subject = SecurityUtils.getSubject();

        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        System.out.println(userInfo.getUsername()+"退出了系统！");
        subject.logout();
        return "sys/login";
    }

    @PostMapping("/register")
    public String registerP(@Valid UserInfo userInfo, BindingResult bindingResult, Model model ){
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                FieldError fieldError = (FieldError) objectError;
                model.addAttribute(fieldError.getField() + "Valid", objectError.getDefaultMessage());
            }
            return "sys/register";
        }else{
            userInfo.setPassword(CryptographyUtil.md5(userInfo.getUsername(),userInfo.getPassword()));
            userinfoDao.save(userInfo);
            return "sys/login";
        }
    }

    @PostMapping("/login")
    public String login(UserInfo userInfo ,HttpServletRequest request, Map<String, Object> map) throws Exception {
        System.out.println("HomeController.login()");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
//        String exception = (String) request.getAttribute("shiroLoginFailure");
//        System.out.println("exception=" + exception);
//        String msg = "";
//        if (exception != null) {
//            if (UnknownAccountException.class.getName().equals(exception)) {
//                System.out.println("UnknownAccountException -- > 账号不存在：");
//                msg = "UnknownAccountException -- > 账号不存在：";
//            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
//                System.out.println("IncorrectCredentialsException -- > 密码不正确：");
//                msg = "IncorrectCredentialsException -- > 密码不正确：";
//            } else if ("kaptchaValidateFailed".equals(exception)) {
//                System.out.println("kaptchaValidateFailed -- > 验证码错误");
//                msg = "kaptchaValidateFailed -- > 验证码错误";
//            } else {
//                msg = "else >> " + exception;
//                System.out.println("else -- >" + exception);
//            }
//        }
//        map.put("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理
        try{
            String password = CryptographyUtil.md5(userInfo.getUsername(),userInfo.getPassword());
            UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(),password);
            token.setRememberMe(true);
            SecurityUtils.getSubject().login(token);
            return "sys/success";
        }catch (Exception e){
            map.put("msg", "账号或者密码错误");
            return "sys/login";
        }



    }

    @RequestMapping("/403")
    public String unauthorizedRole() {
        System.out.println("------没有权限-------");
        return "403";
    }
}